<template>
  <div>
    <div class="__table">
      <el-button @click="dialogOpen('add')"
                 v-if="!search"
                 class="__table_button"><i class="el-icon-plus"></i></el-button>
      <s-table
        :table="table"
        ref="table"
        :control="false"
        :expand="false"
        :index="true"
        :pagination="false"
        @http="tableWatch">
        <el-table-column
          fixed="right"
          align="center"
          slot="operation"
          class-name="operationMore"
          label="操作"
          v-if="!search"
          width="120">
          <template scope="s">
            <el-button type="success" icon="el-icon-edit" size="mini" @click="dialogOpen('PUT', s.row, s.$index)"
                       round></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="tableDelete(s.$index, s.row)"
                       round></el-button>
          </template>
        </el-table-column>
      </s-table>
    </div>
    <s-dialog :dialog="dialog">
      <p slot="title">
        {{dialog.title}}费用承担部门
        <span v-if="dialog.title === '修改'">费用承担部门：{{dialog.row.departmentName.split('/')[dialog.row.departmentName.split('/').length-1]}}</span>
      </p>
      <s-form :form="formDialog" ref="formDialog">
        <el-row>
          <el-col :xs="24" :lg="{span: 11, offset: 0}">
            <el-form-item prop="departmentId" label="费用承担部门">
              <el-cascader
                :options="dialog.bxSupplierDepartmentid"
                v-model="formDialog.departmentId"
                :show-all-levels="false"
                ref="departmentId"
                clearable
                filterable
                change-on-select
                :props="{
                  value: 'key',
                }"
                placeholder="所属部门"
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="{span: 11, offset: 1}">
            <el-form-item prop="money" label="承担金额">
              <el-input-number
                v-model.number="formDialog.money"
                :min="0"
                :max="TRAVEL_moneySum - TRAVEL_moneyUse + dialog.oldMoney"
                placeholder="承担金额"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
      </s-form>
      <el-button slot="footer" @click="dialogSave">保存</el-button>
    </s-dialog>
  </div>
</template>

<script>
  import {AutoVue, AutoPromise} from '~/plugins/Tools';

  let id = 0;

  /**
   * 报销单明细
   departmentId (string, optional): 费用归属机构 $$$true$true$false$$1$vNull,
   money (string, optional): 承担金额 $$$true$true$false$$2$vNull,
   */
  function __formDialog () {
    return {
      departmentId: { value: [], rule: [ 'vNull__change' ] },
      money: { value: '', rule: [ 'vNull', 'vNumber' ] },
    };
  }
  function treefilter (arrayTree) {
    if (typeof arrayTree === 'undefined') return undefined;
    let tree = [];
    arrayTree.forEach(item => {
      if (item.children && item.children.length === 0) {
        delete item.children;
      } else {
        item.children = treefilter(item.children);
      }
      delete item.disabled;
      tree.push(item);
    });
    return tree;
  }

  export default AutoVue({
    name: 'department',
    data: {
      table: {
        column: [
          {'label': '费用归属部门', 'prop': 'departmentName', 'minWidth': '0px'}, {
            'label': '承担金额',
            'prop': 'money',
            'minWidth': '0px',
          },
        ],
        key: 'id',
        muti: false,
      },
      formDialog: __formDialog(),
      loanNum: {},
      dialog: {
        modal: false,
        width: '50%',
        title: '新增',
        oldMoney: 0,
        row: {},
        bxSupplierDepartmentid: [],
        index: '',
      },
    },
    props: {
      init: {
        type: Array,
      },
      search: {
        type: Boolean,
        default: false,
      },
    },
    store: ['TRAVEL_moneyUse', 'TRAVEL_moneySum'],
    methods: {
      tableDelete (index, row) {
        let tableRef = 'table';
        this.$confirm('您将删除该条明细。', '确认删除？', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning',
        }).then(async () => {
          this[tableRef].data.splice(index, 1);
          this.SET('TRAVEL_moneyUse', this.TRAVEL_moneyUse - row.money);
        });
      },
      async dialogOpen (type, more, index) {
        console.log(type);
        if (type) {
          type = type.toUpperCase();
        } else return;
        await AutoPromise([
          async () => {
            let json = await this.get('/dictionaries/getDepartmentTree');
            this.dialog.bxSupplierDepartmentid = treefilter(json);
          },
        ]);
        switch (type) {
        case 'ADD':
          this.dialog.title = '新增';
          this.formDialog.id = 0;
          break;
        case 'PUT':
          this.dialog.title = '修改';
          this.$nextTick(() => {
            this.dialog.oldMoney = more.money;
            this.formDialog = {
              ...this.formDialog,
              ...this.ObjectClone(__formDialog(), more),
            };
            this.formDialog.departmentId = more.departmentIdOld;
          });
          this.dialog.row = more;
          this.dialog.index = index;
          break;
        }
        this.dialog.visible = true;
      },
      dialogSave () {
        if (parseInt(this.formDialog.money) === 0) {
          return this.$alert('承担金额不能为0！', '提示');
        }
        this.VALIDATE('formDialog', option => {
          option.id = id++;
          option.departmentIdOld = option.departmentId;
          option.departmentId = option.departmentId[option.departmentId.length - 1];
          option.departmentName = this.$refs.departmentId.currentLabels[this.$refs.departmentId.currentLabels.length - 1];
          if (this.dialog.index === '') {
            this.table.data.push(option);
          } else {
            this.table.data.splice(this.dialog.index, 1);
            this.table.data.unshift(option);
          }
          this.SET('TRAVEL_moneyUse', this.TRAVEL_moneyUse + option.money - this.dialog.oldMoney);
          this.dialog.dialogInit.call(this);
        });
      },
    },
    mounted: function () {
      if (this.init && this.init.length !== 0) {
        this.table.data = this.init;
      }
    },
  });
</script>

<style scoped lang="scss">
  .card {
    float: left;
    border-radius: 3px;
    box-shadow: 0 2px 10px 1px rgba(0, 0, 0, .1);
    height: 110px;
    width: 300px;
    margin: 15px;
    padding: 25px;
    position: relative;
    vertical-align: top;
    transition: .4s;
    cursor: pointer;
    &:hover {
      box-shadow: 0 10px 20px 1px rgba(0, 0, 0, .1);
      text-decoration: none;
    }
  }

  .card__icon {
    font-size: 24px;
    left: 28px;
    position: absolute;
    top: 25px;
    color: #20a0ff;
  }

  .card__title {
    color: #20a0ff;
    margin-top: 0;
    margin-bottom: 10px;
    margin-left: 40px;
  }

  .card__body {
    line-height: 22px;
    margin-left: 40px;
  }

  @media screen and (max-width: 800px) {
    .card {
      width: calc(100% - 80px);
    }
  }
</style>
